/**
 * 添加或者修改页面
 */
var TDispatchInfoDlg = {
    data: {
        mileageTraveled: ""
    }
};
var submit = 2
layui.use(['table', 'admin', 'ax', 'laydate', 'form'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var laydate = layui.laydate;
    var form = layui.form;

    laydate.render({
        elem: '#startTime'
        , value: new Date()
    });

    laydate.render({
        elem: '#endTime'
        , value: new Date()
    });

    /**
     * 调度单表管理
     */
    var TDispatch = {
        tableId: "tDispatchTable"
    };

    /**
     * 回传单表管理
     */
    var TransportReceipt = {
        tableId: "transportReceiptTable"
    };

    /**
     * Initialize table columns
     */
    TDispatch.initColumn = function () {
        return [[
            { type: 'checkbox' },
            { field: 'id', hide: true, title: 'ID' },
            { width: 460, align: 'center', toolbar: '#tableBar', title: 'Operations' },
            { field: 'startDate', sort: true, title: 'Departure Date', style: 'font-weight: 600;' },
            { field: 'returnTstate', sort: true, title: 'Receipt Status', style: 'font-weight: 600;', templet: '#returnTstateTpl', width: 140 },
            {
                field: 'stateTb', sort: true, title: 'Report Status', style: 'font-weight: 600;',
                templet: function (d) {
                    var str = "";
                    if (d.stateTb == 'NOT_REPORTED') {
                        str += '<span style="color:#ff003b;font-weight: bold;">NOT_REPORTED</span>'
                    } else if (d.stateTb == 'PENDING_REPORT') {
                        str += '<span style="color:#19be6b;font-weight: bold;">PENDING_REPORT</span>'
                    } else {
                        str += '<span style="font-weight: bold;">' + d.stateTb + '</span>'
                    }
                    return str
                }
            },
            { field: 'siji', sort: true, title: 'Driver', style: 'font-weight: 600;', width: 100 },
            { field: 'carnumber', sort: true, title: 'Vehicle Number', style: 'background-color: #dbf1e1;font-weight: 600;', width: 140 },
            { field: 'sijidianhua', sort: true, title: 'Phone', style: 'background-color: #dbf1e1;font-weight: 600;' },
            { field: 'trainNumber', sort: true, title: 'Train Number', style: 'font-weight: 600;' },
            { field: 'fayunTimes', sort: true, title: 'Dispatch Time', style: 'font-weight: 600;', width: 140 },
            { field: 'returnTime', sort: true, title: 'Receipt Time', style: 'font-weight: 600;' },
            { field: 'stateTbTime', sort: true, title: 'Report Time', style: 'font-weight: 600;' },
            { field: 'mileageTraveled', sort: true, title: 'Calculated Mileage', style: 'font-weight: 600;', templet: '#mileageTraveledTpl' },
            { field: 'mileageTraveledYy', sort: true, title: 'Actual Mileage', style: 'font-weight: 600;' },
            { field: 'remain', sort: true, title: 'Stop Count', style: 'font-weight: 600;' },
            { field: 'dispatchNumber', sort: true, title: 'Transport Number', style: 'font-weight: 600;', templet: '#dispatchNumberTpl', width: 180 },
            {
                field: 'tstate', sort: true, title: 'Transport Status', style: 'font-weight: 600;',
                templet: function (d) {
                    var str = "";
                    if (d.tstate == 'IN_TRANSIT') {
                        str += '<i class="layui-icon" lay-event="tooTstateDetailed" style="color: #2b85e4;">&#xe615;</i><span style="color:#ffaa00;font-weight: bold;">IN_TRANSIT</span>'
                    } else if (d.tstate == 'COMPLETED') {
                        str += '<i class="layui-icon" lay-event="tooTstateDetailed" style="color: #2b85e4;">&#xe615;</i><span style="color:#19be6b;font-weight: bold;">COMPLETED</span>'
                    } else {
                        str += '<i class="layui-icon" lay-event="tooTstateDetailed" style="color: #2b85e4;">&#xe615;</i><span style="font-weight: bold;">' + d.tstate + '</span>'
                    }
                    return str
                }
            },

            { field: 'chexing', sort: true, title: 'Vehicle Type', style: 'background-color: #dbf1e1;font-weight: 600;' },
            { field: 'loadingType', sort: true, title: 'Loading Party', style: 'font-weight: 600;' },
            { field: 'loadingPersonnel', title: '<span style="color: #2b85e4;"><i class="layui-icon">&#xe716;</i> Loading Personnel</span>', style: 'color: #2b85e4;', edit: 'text' },

            { field: 'zhunzailiang', sort: true, title: 'Approved Volume', style: 'font-weight: 600;' },
            { field: 'fulllv', sort: true, title: 'Full Load Rate %', style: 'font-weight: 600;', totalRowText: 'Total: ' },
            { field: 'zhuangzaiFileid', hide: true, title: 'Loading Photo ID' },
            { align: 'center', sort: true, toolbar: '#tableBar4', title: 'Loading Photos' },
            { field: 'toovolume', sort: true, title: 'Total Volume m3', style: 'font-weight: 600;', totalRow: true },
            { field: 'tooNum', sort: true, title: 'Total Quantity', style: 'font-weight: 600;', totalRow: true },
            { field: 'matrixingNumber', sort: true, title: 'Converted Quantity', style: 'font-weight: 600;', totalRow: true },
            { field: 'toomoney', sort: true, title: 'Cargo Value', style: 'font-weight: 600;', totalRow: true },
            { field: 'chengyunfangshi', sort: true, title: 'Carriage Method', style: 'font-weight: 600;' },
            { field: 'chengyunleixing', sort: true, title: 'Carriage Type', style: 'font-weight: 600;' },
            { field: 'carrierName', sort: true, title: 'Carrier', style: 'font-weight: 600;' },
            { field: 'lineName', sort: true, title: 'Route', style: 'font-weight: 600;' },
            { field: 'consultMoney', sort: true, title: 'System Reference Price ￥', style: 'font-weight: 600;', templet: '#consultMoneyTpl', totalRow: true },
            { field: 'money', sort: true, title: 'Payment Amount', style: 'font-weight: 600;', totalRow: true },
            { field: 'freightMoney', sort: true, title: 'Freight', style: 'font-weight: 600;', totalRow: true },
            { field: 'loadingMoney', sort: true, title: 'Loading Fee', style: 'font-weight: 600;', totalRow: true },
            { field: 'xiechefei', sort: true, title: 'Unloading Fee', style: 'font-weight: 600;', totalRow: true },
            { field: 'payee', sort: true, title: 'Settlement Object', style: 'font-weight: 600;' },
            { field: 'dianduyuan', sort: true, title: 'Dispatcher', style: 'font-weight: 600;' },
            { field: 'createTime', sort: true, title: 'Dispatch Time', style: 'font-weight: 600;' },
            { field: 'examineName', sort: true, title: 'Reviewer', style: 'font-weight: 600;' },
            { field: 'examineTimes', sort: true, title: 'Review Time', style: 'font-weight: 600;' },
            { field: 'completeName', sort: true, title: 'Completer', style: 'font-weight: 600;' },
            { field: 'completeTimes', sort: true, title: 'Completion Time', style: 'font-weight: 600;' },
            { field: 'operateName', sort: true, title: 'Project', style: 'font-weight: 600;' },
            { field: 'notes', sort: true, title: 'Remarks', style: 'font-weight: 600;' },
        ]];
    };

    /**
     * Click search button
     */
    TDispatch.search = function () {
        var queryData = {};
        queryData['condition'] = $("#condition").val();
        queryData['tstate'] = $("#tstate").val();
        queryData['stateTb'] = $("#stateTb").val();
        queryData['returnTstate'] = $("#returnTstate").val();
        queryData['startTime'] = $("#startTime").val();
        queryData['endTime'] = $("#endTime").val();
        queryData['operateId'] = $("#operateId").val();
        queryData['carrierId'] = $("#carrierId").val();
        queryData['lineName'] = $("#lineName").val();
        queryData['carrierNames'] = $("#carrierNames").val();
        table.reload(TDispatch.tableId, {
            where: queryData, page: { curr: 1 },
            done: function () {
            }
        });
    };

    // Render table
    var tableResult = table.render({
        elem: '#' + TDispatch.tableId,
        url: Feng.ctxPath + '/tDispatch/list',
        page: true,
        limit: 240,
        limits: [60, 120, 240, 360, 480, 600, 2000, 5000],
        height: 400,
        totalRow: true,
        toolbar: '#toolbarDemo', //Enable header toolbar and bind left template to it
        defaultToolbar: ['filter', 'exports', 'print'],
        cellMinWidth: 100,
        cols: TDispatch.initColumn()
    });

    // Edit cell event
    table.on('edit(' + TDispatch.tableId + ')', function (obj) {
        var data = obj.data;//Get all key-value pairs of the row
        var value = obj.value;//Modified value
        var field = obj.field;
        if (field == 'loadingPersonnel') {
            var ajax = new $ax(Feng.ctxPath + "/orderTransportDispatch/edititem?id=" + data.id + "&loadingPersonnel=" + value, function (data) {
                if (data.success) {
                    Feng.success("Modification successful!");
                } else {
                    Feng.error("Modification failed! " + data.message);
                }
            }, function (data) {
                Feng.error("Modification failed! " + data.responseJSON.message + "!");
            });
            ajax.start();
        }
    });

    // Search button click event
    $('#btnSearch').click(function () {
        TDispatch.search();
    });

    // In-transit monitoring button click event
    $('#monitoring').click(function () {
        window.open('http://39.105.212.172:16061/manager.html');
    });


    TDispatch.aaa = function (row) {
        var ajax = new $ax(Feng.ctxPath + "/tDispatch/update5?id=" + row.id, function (data) {
            if (data.success) {
                Feng.success("Reported successfully!");
                TDispatch.search();
            } else {
                Feng.error("Report failed! " + data.message);
            }
        }, function (data) {
            Feng.error("Report failed! " + data.responseJSON.message + "!");
        });
        ajax.start();
    }

    TDispatch.update6 = function (row) {
        var ajax = new $ax(Feng.ctxPath + "/tDispatch/update6?id=" + row.id, function (data) {
            if (data.success) {
                Feng.success("Withdrawn successfully!");
                TDispatch.search();
            } else {
                Feng.error("Withdrawal failed! " + data.message);
            }
        }, function (data) {
            Feng.error("Withdrawal failed! " + data.responseJSON.message + "!");
        });
        ajax.start();
    }

    $('#btnSearch4').click(function () {
        var checkRows = table.checkStatus(TDispatch.tableId);
        var DataArray = checkRows.data;
        for (var i = 0; i < DataArray.length; i++) {
            var row = DataArray[i]
            var l = -1;
            if (row.stateTb == "PENDING_REPORT") {
                layer.msg('Selected items have already been reported', { icon: 0 }, function () {
                    // layer.msg('Callback after prompt box closes');
                });
                l = 1
                break;
            }

        }

        if (l == -1) {
            for (var k = 0; k < DataArray.length; k++) {
                var row = DataArray[k]
                TDispatch.aaa(row);
            }
        }
    });

    $('#btnSearch5').click(function () {
        var checkRows = table.checkStatus(TDispatch.tableId);
        var DataArray = checkRows.data;
        for (var i = 0; i < DataArray.length; i++) {
            var row = DataArray[i]
            var l = -1;
            if (row.stateTb == "NOT_REPORTED") {
                layer.msg('Selected items are already in [NOT_REPORTED] state', { icon: 0 }, function () {
                    // layer.msg('Callback after prompt box closes');
                });
                l = 1
                break;
            }

        }

        if (l == -1) {
            for (var k = 0; k < DataArray.length; k++) {
                var row = DataArray[k]
                TDispatch.update6(row);
            }
        }
    });



    /**
     * Click arrive at warehouse
     * @param data Row data when clicking the button
     */
    TDispatch.onDaochangItem = function (data) {
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/tDispatch/editdaocang", function (data) {
                if (data.success) {
                    Feng.success("Operation successful!");
                    table.reload(TDispatch.tableId);
                } else {
                    Feng.error("Operation failed! " + data.message);
                }
            }, function (data) {
                Feng.error("Operation failed! " + data.responseJSON.message + "!");
            });
            ajax.set("id", data.id);
            ajax.start();
        };
        Feng.confirm("Confirm arrival?", operation);
    };

    /**
     * Click leave warehouse
     * @param data Row data when clicking the button
     */
    TDispatch.onLichangItem = function (data) {
        let _data = data;
        layer.confirm('Confirm departure?', function (index) {
            layer.close(index);
            var ajax = new $ax(Feng.ctxPath + "/orderTransportDispatch/getTs", function (data) {
                if (data.success) {
                    quuedinglichang(_data);
                } else {
                    // Check if it's a 400 status code
                    if (data.code === 400) {
                        // Disable related buttons
                        $('.layui-btn').attr('disabled', 'disabled');
                        // Display error message
                        layer.alert(data.message, {
                            title: 'Error',
                            icon: 2
                        });
                    } else {
                        // Other errors, display confirmation box
                        let ts = layer.open({
                            title: 'Prompt',
                            content: data.message,
                            btn: ['Confirm', 'Cancel'],
                            yes: function (index, layero) {
                                layer.close(index);
                                quuedinglichang(_data);
                            },
                            btn2: function (index, layero) {
                                layer.close(index);
                            }
                        });
                    }
                }
            },function (xhr) {
                // Handle HTTP errors
                if (xhr.status === 400) {
                    // Disable submit button
                    $('button[lay-submit]').attr('disabled', 'disabled');
                    layer.alert("Request failed: " + xhr.responseText, {
                        title: 'Error',
                        icon: 2
                    });
                } else {
                    Feng.error("Operation failed! " + xhr.responseText + "!");
                }
            });
            // Disable related buttons to prevent duplicate submissions
            // $('.layui-btn').attr('disabled', 'disabled');
            ajax.set(data.field);
            ajax.start();
        });
    };

    /**
     * Electronic signing
     * @param data Row data when clicking the button
     */
    TDispatch.onDianZiQianYueItem = function (data) {
        let title = "Confirm electronic signature?";
        if (data.sginKey != "") {
            title = "Electronic signature information has been synchronized, do you want to overwrite it?";
        }
        layer.confirm(title, function (index) {
            layer.close(index);
            var msg;
            $.ajax({
                url: Feng.ctxPath + "/tDispatch/dianziqianyue",
                data: { id: data.id },
                cache: false,
                dataType: "json",
                beforeSend: function () {
                    msg = layer.msg('Submitting... Please wait patiently', {
                        icon: 16,
                        shade: [0.2, '#000'], //0.1透明度的白色背景
                        time: false
                    });
                },
                success: function (data) {
                    layer.close(msg);
                    if (data.success) {
                        Feng.success("Submit successful!");
                        table.reload(TDispatch.tableId);
                    } else {
                        Feng.error("Submit failed! " + data.message);
                    }
                },
                error: function (data) {
                    layer.close(msg);
                    Feng.error("Submit failed! " + data.responseJSON.message)
                }
            })
        });
    };

    function quuedinglichang(data) {
        var msg;
        $.ajax({
            url: Feng.ctxPath + "/tDispatch/editlicahng",
            data: { id: data.id },
            cache: false,
            dataType: "json",
            beforeSend: function () {
                msg = layer.msg('Submitting... Please wait patiently', {
                    icon: 16,
                    shade: [0.2, '#000'], //0.1透明度的白色背景
                    time: false
                });
            },
            success: function (data) {
                layer.close(msg);
                if (data.success) {
                    Feng.success("Submit successful!");
                    table.reload(TDispatch.tableId);
                } else {
                    Feng.error("Submit failed! " + data.message);
                }
            },
            error: function (data) {
                layer.close(msg);
                Feng.error("Submit failed! " + data.responseJSON.message)
            }
        })
    }

    //Query warehouse area
    form.on('select(operateId)', function () {
        $("#carrierId").empty();
        $.ajax({
            url: Feng.ctxPath + '/basicCarrier/Querylist',
            dataType: "json",   //返回格式为json
            async: false,
            data: { "operateId": $("#operateId").val() },    //parameter value
            type: "post",   //request method
            success: function (data) {
                if (data.length > 0) {
                    var str = "<option value=''>Select Carrier</option>";
                    $.each(data, function (key, value) {
                        str += "<option value='" + value.id + "'>" + value.carrierName + "</option>";
                    });
                    $("#carrierId").html(str);
                }
            }
        });
        form.render('select');
    });

    // 工具条点击事件
    table.on('tool(' + TDispatch.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'tooTstateDetailed') {
            layer.open({
                type: 2,
                title: 'Transport Information',
                area: ['1100px', '500px'],
                anim: 5,
                content: Feng.ctxPath + '/transportMsg?dispatchNumber=' + data.dispatchNumber,
            });
        } else if (layEvent === 'tooConsultMoneyDetailed') {
            layer.open({
                type: 2,
                title: 'Cost Information',
                area: ['1100px', '500px'],
                anim: 5,
                content: Feng.ctxPath + '/transportCost?dispatchNumber=' + data.dispatchNumber,
            });
        } else if (layEvent === 'chexiaod') {
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/orderTransportDispatch/removeDispatchNumberBySpec?dispatchNumber=" + data.dispatchNumber, function (data) {
                    if (data.success) {
                        Feng.success("Withdrawal successful!");
                        table.reload(TDispatch.tableId);
                    } else {
                        Feng.error("Withdrawal failed! " + data.message);
                    }
                }, function (data) {
                    Feng.error("Withdrawal failed! " + data.responseJSON.message + "!");
                });
                ajax.start();
            };
            Feng.confirm("Confirm withdrawal?", operation);
        } else if (layEvent === 'bianjid') {
            submit = 2
            layer.open({
                type: 2,
                title: 'Edit: ' + data.carnumber,
                area: ['1000px', '550px'],
                anim: 5,
                content: Feng.ctxPath + '/orderTransportDispatch/tochecktooyedit?dispatchNumber=' + data.dispatchNumber,
                end: function () {
                    if (submit == 1) {
                        table.reload(TDispatch.tableId);
                    }
                }
            });
        } else if (layEvent === 'tiaozhengd') {
            submit = 2
            layer.open({
                type: 2,
                title: 'Adjust: ' + data.carnumber,
                area: ['1000px', '550px'],
                anim: 5,
                content: Feng.ctxPath + '/orderTransportDispatch/tochecktooytiaozhengd?dispatchNumber=' + data.dispatchNumber,
                end: function () {
                    if (submit == 1) {
                        table.reload(TDispatch.tableId);
                    }
                }
            });
        } else if (layEvent === 'tiaozhengcost') {
            submit = 2
            layer.open({
                type: 2,
                title: 'Adjust Cost',
                area: ['1200px', '700px'],
                anim: 5,
                content: Feng.ctxPath + '/orderTransportDispatch/toeditcost?dispatchNumber=' + data.dispatchNumber,
                end: function () {
                    if (submit == 1) {
                        table.reload(TDispatch.tableId);
                    }
                }
            });
        } else if (layEvent === 'edit') {
            submit = 2
            layer.open({
                type: 2,
                title: 'Modify Waybill Information',
                area: ['1000px', '550px'],
                anim: 5,
                content: Feng.ctxPath + '/tDispatch/toedit?id=' + data.id,
                end: function () {
                    if (submit == 1) {
                        table.reload(TDispatch.tableId);
                    }
                }
            });
        } else if (layEvent === 'daochang') {
            TDispatch.onDaochangItem(data)
        } else if (layEvent === 'lichang') {
            TDispatch.onLichangItem(data)
        } else if (layEvent === 'dianziqianyue') {
            TDispatch.onDianZiQianYueItem(data)
        } else if (layEvent === 'wancheng') {
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/tDispatch/accomplishUnitGoods", function (data) {
                    Feng.success("Operation successful!");
                    table.reload(TDispatch.tableId);
                }, function (data) {
                    Feng.error("Operation failed! " + data.responseJSON.message + "!");
                });
                ajax.set("id", data.id);
                ajax.start();
            };
            Feng.confirm("Confirm completion?", operation);
        } else if (layEvent === 'tooDetailed') {
            layer.open({
                type: 2,
                title: 'Delivery Dispatch Information',
                area: ['1250px', '570px'],
                anim: 5,
                content: Feng.ctxPath + '/tDispatch/tooDetailed?dispatchNumber=' + data.dispatchNumber,
            });
        } else if (layEvent === 'huidan') {
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/orderTransportDispatch/huidan?id=" + data.id, function (data) {
                    if (data.success) {
                        Feng.success("Confirmation successful!");
                        table.reload(TDispatch.tableId);
                    } else {
                        Feng.error("Confirmation failed! " + data.message);
                    }
                }, function (data) {
                    Feng.error("Confirmation failed! " + data.responseJSON.message + "!");
                });
                ajax.start();
            };
            Feng.confirm("Confirm receipt?", operation);

        } else if (layEvent === 'dzqcscz') {
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/tDispatch/dzqcscz?id=" + data.id, function (data) {
                    if (data.success) {
                        Feng.success("Reset successful!");
                        table.reload(TDispatch.tableId);
                    } else {
                        Feng.error("Reset failed! " + data.message);
                    }
                }, function (data) {
                    Feng.error("Reset failed! " + data.responseJSON.message + "!");
                });
                ajax.start();
            };
            Feng.confirm("Confirm resetting electronic signature count?", operation);
        } else if (layEvent === 'hdyichang') {
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/orderTransportDispatch/hdyichang?id=" + data.id, function (data) {
                    if (data.success) {
                        Feng.success("Operation successful!");
                        table.reload(TDispatch.tableId);
                    } else {
                        Feng.error("Operation failed！" + data.message);
                    }
                }, function (data) {
                    Feng.error("Operation failed! " + data.responseJSON.message + "!");
                });
                ajax.start();
            };
            Feng.confirm("Confirm exception?", operation);
        } else if (layEvent === 'yhdyichang') {
            layer.open({
                type: 2,
                title: 'Receipt Exception',
                area: ['1250px', '570px'],
                anim: 5,
                content: Feng.ctxPath + '/tDispatch/tooYhdyichang?id=' + data.id,
                end: function () {
                    if (submit == 1) {
                        table.reload(TDispatch.tableId);
                    }
                }
            });
        } else if (layEvent === 'yichangchuli') {
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/orderTransportDispatch/huidan?id=" + data.id, function (data) {
                    if (data.success) {
                        Feng.success("Operation successful!");
                        table.reload(TDispatch.tableId);
                    } else {
                        Feng.error("Operation failed! " + data.message);
                    }
                }, function (data) {
                    Feng.error("Operation failed! " + data.responseJSON.message + "!");
                });
                ajax.start();
            };
            Feng.confirm("Confirm processing?", operation);
        } else if (layEvent === 'count') {
            submit = 2
            layer.open({
                type: 2,
                title: 'Calculate Mileage',
                area: ['900px', '600px'],
                anim: 5,
                content: Feng.ctxPath + '/transportReceipt/toCount?dispatchNumber=' + data.dispatchNumber,
                end: function () {
                    if (submit == 1) {
                        if (TDispatchInfoDlg.data.mileageTraveled != "" && TDispatchInfoDlg.data.mileageTraveled != null) {
                            var ajax = new $ax(Feng.ctxPath + "/orderTransportDispatch/edititem?id=" + data.id + "&mileageTraveled=" + TDispatchInfoDlg.data.mileageTraveled, function (data) {
                                if (data.success) {
                                    Feng.success("Modification successful!");
                                    table.reload(TDispatch.tableId);
                                } else {
                                    Feng.error("Modification failed! " + data.message);
                                }
                            }, function (data) {
                                Feng.error("Modification failed! " + data.responseJSON.message + "!");
                            });
                            ajax.start();
                        }
                    }
                }
            });
        } else if (layEvent === 'paymentProve') {
            //Construct image array
            var items = [];
            if (data.zhuangzaiFileid != '') {
                var obj = {};
                obj.src = '/system/previewa/' + data.zhuangzaiFileid;
                obj.title = 'Preview Image';
                items.push(obj)
                //Define options (if needed)
                var options = {
                    index: 0 // This option indicates you will start from the first image
                };
                //Initialize plugin
                var viewer = new PhotoViewer(items, options);
            } else {
                Feng.info("No photos available!");
            }
        }
    });

    /**
     * Initialize table columns
     */
    TransportReceipt.initColumn = function () {
        return [[
            { field: 'id', hide: true, title: 'ID' },
            { align: 'center', toolbar: '#tableBarde', title: 'Operations', width: 500 },

            { field: 'printNumHx', title: 'Retail Print Delivery Note Times', style: 'font-weight: 600;' },
            { field: 'stockPort', title: '<span style="color: #2b85e4;"><i class="layui-icon">&#xe716;</i> Stock Area</span>', style: 'color: #2b85e4;', edit: 'text' },
            { field: 'deliverys', title: '<span style="color: #2b85e4;"><i class="layui-icon">&#xe716;</i> Delivery Sequence</span>', style: 'color: #2b85e4;', edit: 'text' },

            { field: 'getUnitid', hide: true, title: 'Unloading Unit ID' },
            { field: 'getUnit', title: 'Unit', style: 'background-color: #dbf1e1;font-weight: 600;', width: 140 },
            { field: 'getLocation', title: 'Address', style: 'background-color: #dbf1e1;font-weight: 600;', width: 160 },
            { field: 'getLocationid', hide: true, title: 'Unloading Address ID' },
            { field: 'getPeople', hide: true, title: 'Contact Person', style: 'background-color: #dbf1e1;font-weight: 600;' },
            { field: 'getTel', hide: true, title: 'Contact Phone', style: 'background-color: #dbf1e1;font-weight: 600;' },
            { field: 'longitude', title: 'Longitude', style: 'font-weight: 600;' },
            { field: 'latitude', title: 'Latitude', style: 'font-weight: 600;' },
            { field: 'kilometer', title: 'Kilometers', style: 'font-weight: 600;' },

            { field: 'num', sort: true, title: 'Quantity' },
            { field: 'volume', title: 'Volume' },

            { field: 'sdtstate', sort: true, title: 'Delivery Status', style: 'font-weight: 600;' },
            { field: 'sdfileId', title: 'Electronic Signature', templet: '#sdpaymentProveTpl', event: 'sdpaymentProve' },
            { field: 'sdtime', sort: true, title: 'Delivery Time' },
            { field: 'sdusername', title: 'Delivery Personnel' },

            { field: 'tstate', sort: true, title: 'Receipt Status', style: 'font-weight: 600;' },
            { field: 'fileId', title: 'Receipt', templet: '#paymentProveTpl', event: 'paymentProve' },
            { field: 'time', sort: true, title: 'Return Time' },
            { field: 'username', title: 'Return Personnel' },
        ]];
    };

    // 单击行事件
    table.on('row(' + TDispatch.tableId + ')', function (obj) {
        var data = obj.data;
        $('div[lay-id="' + TDispatch.tableId + '"]').find(".layui-table-body tr ").attr({ "style": "background:#FFFFFF" });//其他tr恢复原样
        $('div[lay-id="' + TDispatch.tableId + '"]').find(obj.tr.selector).attr({ "style": "background:#e6e6e6" });//改变当前tr颜色
        receipt(data);
    });

    function receipt(dataas) {
        var dispatchNumber;
        if (dataas != null) {
            dispatchNumber = dataas.dispatchNumber;
        } else {
            dispatchNumber = 'nodata';
        }

        // 渲染表格
        var tableResult = table.render({
            elem: '#' + TransportReceipt.tableId,
            url: Feng.ctxPath + '/transportReceipt/list?dispatchNumber=' + dispatchNumber,
            page: true,
            limit: 20,
            height: 390,
            toolbar: '#toolbarDemo', //开启头部工具栏，并为其绑定左侧模板
            defaultToolbar: ['filter', 'exports', 'print'],
            cellMinWidth: 100,
            cols: TransportReceipt.initColumn()
        });

        // 编辑单元格 事件
        table.on('edit(' + TransportReceipt.tableId + ')', function (obj) {
            var data = obj.data;//得到所在行所有键值
            var value = obj.value;//修改后的值
            var field = obj.field;
            if (field == 'stockPort') {
                var ajax = new $ax(Feng.ctxPath + "/transportReceipt/editStockPort?id=" + data.id + "&stockPort=" + value, function (data) {
                    if (data.success) {
                        Feng.success("Modification successful!");
                    } else {
                        Feng.error("Modification failed! " + data.message);
                    }
                }, function (data) {
                    Feng.error("Modification failed! " + data.responseJSON.message + "!");
                });
                ajax.start();
            }
            if (field == 'deliverys') {
                var ajax = new $ax(Feng.ctxPath + "/transportReceipt/editStockPort?id=" + data.id + "&deliverys=" + value, function (data) {
                    if (data.success) {
                        Feng.success("Modification successful!");
                    } else {
                        Feng.error("Modification failed! " + data.message);
                    }
                }, function (data) {
                    Feng.error("Modification failed! " + data.responseJSON.message + "!");
                });
                ajax.start();
            }
        });

        // 工具条点击事件
        table.on('tool(' + TransportReceipt.tableId + ')', function (obj) {
            var data = obj.data;
            if (obj.event === 'paymentProve') {
                //构建图像数组
                var items = [];
                if (data.fileId != '') {
                    var obj = {};
                    obj.src = '/transportReceipt/show?fileId=' + data.fileId;
                    obj.title = 'Preview Image';
                    items.push(obj)
                    //定义选项（如果需要）
                    var options = {
                        index: 0 // 此选项表示您将从第一张图片开始
                    };
                    //初始化插件
                    var viewer = new PhotoViewer(items, options);
                } else {
                    Feng.info("No photos available!");
                }
            } else if (obj.event === 'sdpaymentProve') {
                //构建图像数组
                var items = [];
                if (data.sdfileId != '') {
                    var obj = {};
                    obj.src = '/transportReceipt/show?fileId=' + data.sdfileId;
                    obj.title = 'Preview Image';
                    items.push(obj)
                    //定义选项（如果需要）
                    var options = {
                        index: 0 // 此选项表示您将从第一张图片开始
                    };
                    //初始化插件
                    var viewer = new PhotoViewer(items, options);
                } else {
                    Feng.info("No photos available!");
                }
            } else if (obj.event === 'huowu') {
                layer.open({
                    type: 2,
                    title: 'Cargo Details',
                    area: ['1100px', '500px'],
                    anim: 5,
                    content: Feng.ctxPath + '/transportDispatch?dispatchNumber=' + data.dispatchNumber + '&getUnitid=' + data.getUnitid + '&getLocationid=' + data.getLocationid,
                });
            } else if (obj.event === 'gaidizhi') {
                layer.open({
                    type: 2,
                    title: 'Modify Address',
                    area: ['1000px', '800px'],
                    content: Feng.ctxPath + '/orderTransportDispatch/toGaidizhi?id=' + data.getLocationid + "&setLocationId=" + data.setLocationId,
                    end: function () {
                        receipt(dataas);
                    }
                });
            } else if (obj.event === 'print') {
                layer.open({
                    type: 2,
                    title: 'Print Delivery Note',
                    area: ['750px', '550px'],
                    anim: 5,
                    content: Feng.ctxPath + '/tDispatch/print?dispatchNumber=' + data.dispatchNumber + '&getUnitid=' + data.getUnitid + '&getLocationid=' + data.getLocationid,
                });
            } else if (obj.event === 'printTy') {
                layer.open({
                    type: 2,
                    title: 'Print Consignment Note',
                    area: ['990px', '550px'],
                    anim: 5,
                    content: Feng.ctxPath + '/tDispatch/printTy?dispatchNumber=' + data.dispatchNumber + '&getUnitid=' + data.getUnitid + '&getLocationid=' + data.getLocationid,
                });
            } else if (obj.event === 'songda') {
                var operation = function () {
                    var ajax = new $ax(Feng.ctxPath + "/tDispatch/editsongda", function (data) {
                        if (data.success) {
                            Feng.success("Operation successful!");
                            receipt(dataas);
                        } else {
                            Feng.error("Modification failed! " + data.message);
                        }
                    }, function (data) {
                        Feng.error("Operation failed! " + data.responseJSON.message + "!");
                        receipt(dataas);
                    });
                    ajax.set("id", data.id);
                    ajax.set("dispatchNumber", data.dispatchNumber);
                    ajax.set("getUnitid", data.getUnitid);
                    ajax.set("getUnit", data.getUnit);
                    ajax.set("getLocationid", data.getLocationid);
                    ajax.set("getLocation", data.getLocation);
                    ajax.start();
                };
                Feng.confirm("Confirm delivery?", operation);
            } else if (obj.event === 'qianshou') {
                layer.open({
                    type: 2,
                    title: 'Sign and Upload Receipt',
                    area: ['750px', '550px'],
                    anim: 5,
                    content: Feng.ctxPath + '/transportReceipt/edit_uploads?id=' + data.id,
                    end: function () {
                        receipt(dataas);
                    }
                });
            } else if (obj.event === 'qianshou_update') {
                layer.open({
                    type: 2,
                    title: 'Modify Receipt',
                    area: ['750px', '550px'],
                    anim: 5,
                    content: Feng.ctxPath + '/transportReceipt/edit_uploads?id=' + data.id,
                    end: function () {
                        receipt(dataas);
                    }
                });
            } else if (obj.event === 'printHx') {
                layer.open({
                    type: 2,
                    title: 'Print Retail Delivery Note',
                    area: ['990px', '550px'],
                    anim: 5,
                    content: Feng.ctxPath + '/tDispatch/printHx?dispatchNumber=' + data.dispatchNumber + '&getLocationid=' + data.getLocationid + '&startDate=' + dataas.startDate,
                });
            } else if (obj.event === 'updatexsr') {
                layer.open({
                    type: 2,
                    title: 'Change Store Recipient',
                    area: ['990px', '550px'],
                    anim: 5,
                    content: Feng.ctxPath + '/tDispatch/toUpdatexsr?dispatchNumber=' + data.dispatchNumber + '&xlbClientId=' + data.xlbClientId,
                });
            } else if (obj.event === 'printHxCkd'){
                layer.open({
                    type: 2,
                    title: 'Print Sales Delivery Note',
                    area: ['990px', '550px'],
                    anim: 5,
                    content: Feng.ctxPath + '/tDispatch/printHxCkd?dispatchNumber=' + data.dispatchNumber + '&getLocationid=' + data.getLocationid+ '&startDate=' + dataas.startDate,
                });
            }
        });
    };
});